<template>
    <el-row justify="end">
      <el-col :span="24" style="text-align: left;">
        <el-button @click="addUser" type="primary">添加班级信息</el-button>
      </el-col>
    </el-row>
    <el-table
      :data="
        tableData.filter(
          (data) =>
            !search || data.name.toLowerCase().includes(search.toLowerCase())
        )
      "
      :header-cell-style="{background:'#f4f3f9',color:'#606266', fontSize: '12px'}"
      :cell-style = "{fontSize: '12px'}"
      style="width: 100%; margin-top: 10px;"
    >
      <!--
      <el-table-column
        prop="id"
        label="序号"
        width="50">
      </el-table-column>
      -->
      <el-table-column prop="classId" v-if="false"> </el-table-column>
      <el-table-column label="班级" prop="studentClass"> </el-table-column>
      <el-table-column label="二维码" align="right">
        <template #default="scope">
            <img :src="scope.row.codeqr" width="200"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="right">
        <template #default="scope">
            <el-popconfirm title="确认删除该条数据吗?" confirm-button-text="确认"
              cancel-button-text="取消" @confirm="delDistrict(scope.row)">
              <template #reference>
                <el-button  size="small" type="danger">删除</el-button>
              </template>
            </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      small="true"
      background
      layout="prev, pager, next"
      :page-size="5"
      :total="total"
      :current-page="currentPage"
      @current-change="changePage"
      style="margin-top: 30px;">
    </el-pagination>
    <el-drawer
    title="编辑"
    v-model="drawer"
    v-show="drawer"
    :lock-scroll="false"
    :with-header="true">
        <el-form :label-position="labelPosition" label-width="80px" :model="formLabelAlign" ref="ruleFormRef" :rules="rules">
            <el-upload
              class="upload-demo"
              drag
              action="http://101.43.209.55:3001/uploadQr"
              :on-success="showSuccess"
              :headers="token"
              multiple>
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb，上传班级群二维码</div>
            </el-upload>
        </el-form>
    </el-drawer>
  </template>
  <script>
  import { getDistrict, addDistrict, updateDistrict, deleteDistrict } from "../api/district.js"
  import { getDepartment } from "../api/department.js"
  import { getRoles } from "../api/role.js"
  export default {
    data() {
      let checkPhone = (rule, value, callback) => {
          let phoneReg = /^1[3456789]\d{9}$/;
          if(phoneReg.test(value)) {
            callback();
          }
          else {
            return callback(new Error('请输入正确手机号'));
          }
      }
      let checkPwd = (rule, value, callback) => {
          if (value === '') {
            callback(new Error('请输入密码'));
          } else {
            let pwdReg = /^(?=.*[a-zA-Z])(?=.*\d).{6,10}$/;
            if (pwdReg.test(value)) {
              callback();
            }
            else {
              callback(new Error('请输入包含数字、字母，且长度6位以上密码'));
            }
          }
      }
      let confirmPwd = (rule, value, callback) => {
          if (value === '') {
            callback(new Error('请再次输入密码'));
          } else if (value !== this.formLabelAlign.pwd) {
            callback(new Error('两次输入密码不一致!'));
          } else {
            callback();
          }
      };
      return {
        tableData: [
        ],
        search: "",
        drawer: false,
        labelPosition: 'left',
        formLabelAlign: {
        },
        queryParams: {
          page: 1,
          size: 5
        },
        total: '',
        currentPage: 1,
        searchInput: '',
        departmentList: [],
        roles: [],
        rules: {
            districtName: [
              { required: true, message: '请输入小区名称', trigger: 'blur' },
              { min: 2, max: 100, message: '长度在 2 到 4 个字符', trigger: 'blur' }
            ],
            departmentId: [
              { required: true, message: '请选择部门', trigger: 'change' }
            ]
        },
        ifEdit: false,
        token: { authorization: localStorage.getItem("token") }
      };
    },
    methods: {
      showSuccess(response, file, fileList) {
        if(response.status == 'ok') {
          this.$message({
                type: 'success',
                message: `上传成功！`
          })
        }
      },
      /**选择部门 */
      handleNodeClick(nodeobj) {
        this.formLabelAlign.organizationId = nodeobj.value;
      },
      async onAdd() {
        this.ifEdit = false;
        this.$refs['ruleFormRef'].validate(async (valid) => {
          if(valid) {
            let result = await addDistrict(this.formLabelAlign);
            if(result.data.status == "invalid") {
              this.$message({
                type: 'info',
                message: `小区已存在`
              });
            }
            else if(result.data.status == "ok") {
              this.$message({
                type: 'success',
                message: `添加成功！`
              });
              this.formLabelAlign = {};
              this.getDistrict();
            }
          }
          else {
            console.log("validate error")
          }
        })
      },
      async onSubmit() {
        this.ifEdit = false;
        this.$refs['ruleFormRef'].validate(async (valid) => {
          if(valid) {
            let result = await updateDistrict(this.formLabelAlign);
            if(result.data.status == "invalid") {
              this.$message({
                type: 'info',
                message: `小区已存在`
              });
            }
            else if(result.data.status == "ok") {
              this.$message({
                type: 'success',
                message: `更新成功！`
              });
              this.formLabelAlign = {};
              this.getDistrict();
            }
          }
          else {
            console.log("validate error")
          }
        })
      },
      async getDistrictList() {
        this.queryParams.user = localStorage.getItem("user");
        let result = await getDistrict(this.queryParams);
        console.log(result);
        if(result.data.status == 'ok') {
          this.tableData = result.data.districtList;
          this.total = result.data.total
        }
      },
      updateDept(departments) {
        for(let j = 0; j < departments.length; j++) {
          departments[j].label = departments[j].organizationName;
          departments[j].value = departments[j].organizationId;
          for(let i in departments[j]) {
            if(i == "children") {
              this.updateDept(departments[j].children);
            }
          }
        }
      },
      async getDepartment() {
        this.queryParams.user = localStorage.getItem("user");
        let result = await getDepartment(this.queryParams);
        if(result.data.status == 'ok') {
          let departments = result.data.departments;
          this.updateDept(departments);
          this.departmentList = departments;
        };
  
      },
      addUser() {
  
      },
      async delDistrict(row) {
        console.log(row);
        let result = await deleteDistrict({ classId: row.classId });
        if(result.data.status = 'ok') {
          this.$message({
                type: 'success',
                message: `删除成功！`
          });
          this.getDistrictList();
        }
      },  
      addUser() {
        this.drawer = true;
      },
      editUser(row) {
        this.ifEdit = true;
        console.log(row);
        this.formLabelAlign.districtId = row.districtId;
        this.formLabelAlign.districtName = row.districtName;
        this.formLabelAlign.departmentId = row.organizationId;
        this.drawer = true
      },
      changePage(e) {
        this.currentPage = e;
        this.queryParams.page = e;
        this.getManagerList();
      },
      async searchData() {
        console.log(this.searchInput);
        let result = await search({'search': this.searchInput});
        if(result.data.status == 'ok') {
          this.tableData = result.data.userList;
        }
      },
      async exportData() {
        let userName = localStorage.getItem("user");
        let result = await exportFile(userName);
        console.log(result);
      },
      async getRoleList() {
        let result = await getRoles();
        this.roles = result.data.result;
      }
    },
    mounted() {
      this.getDistrictList();
    }
  };
  </script>
  <style scoped>
  </style>